const {
  clearEmpty,
  getType,
  isStr,
  isNum,
  isArr,
  isObj,
  isUnd,
} = require('~/utils')

function genFrom(model) {
  let form = []
  for (let field in model) {
    const option = model[field]
    const type = isUnd(option.type) ? 'string' : getType(option.type)

    let formItem = { field }
    for (let key in option) { formItem[key] = option[key] }
    formItem.type = type
    form.push(formItem)
  }

  return form
}

function verify(form, data) {
  let result = {}
  for (let prop in data) {
    form.forEach(item => {
      if (prop !== item.field) { return }
      const field = data[prop]
      const validate = item.validate
      result[prop] = {}

      // 支持required
      let isObjHasVal = false
      if (isObj(field)) {
        for (let key in field) { isObjHasVal = isObjHasVal || !!field[key] }
      }
      const isStrHasVal = (isStr(field) || isNum(field)) && field
      const isArrHasVal = isArr(field) && field.length > 0
      const hasVal = isArrHasVal || isObjHasVal || isStrHasVal
      const isRequired = validate && validate.required && !hasVal
      if (isRequired) { result[prop].required = true }

      // 自动检测并转换数字类型
      const isNumber = /^(-?\d+)(\.\d+)?$/g.test(field)
      if (isNum(item.type)) {
        if (field && !isNumber) {
          result[prop].typeerr = true
        } else {
          data[prop] = +data[prop]
        }
      }

      // 支持自定义正则 validate: { reg: }
      const hasReg = validate && validate.reg
      if (!hasReg) { return }
      const reg = new RegExp(validate.reg)
      if (field && !reg.test(field)) {
        result[prop].typeerr = true
      }
    })
  }
  return clearEmpty(result)
}

function genModel (data) {
  let model = {}
  for (let field in data) {
    model[field] = data[field].type || ''

    const subform = data[field].subform
    if (!subform) { continue }
    for (let subField in subform) {
      model[field][subField] = subform[subField].type || ''
    }
  }
  return model
}

class Model {
  constructor(_model) {
    this._model = _model
    this.form = genFrom(_model)
    this.model = genModel(_model)
  }

  validate (data) {
    const result = verify(this.form, data)
    const isPass = Object.keys(result).length === 0
    return isPass
            ? Promise.resolve(clearEmpty(data))
            : Promise.reject(result)
  }

  parse () {
  }
}

export default Model
